/*
 * @# FollowController.java 2011-12-22 下午05:43:15
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.user.action;


import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ianswer.px.common.SessionContextHolder;
import com.ianswer.px.common.annotation.SessionAware;
import com.ianswer.px.user.entity.User;
import com.ianswer.px.user.service.UserService;

/**
 * @author pananz
 */
@SessionAware
@Controller
public class UsersController {

	@Resource(name = "userService")
	private UserService userService;

	/**
	 * 转到修改秀客信息页面
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public String show(Model model) {
		User user = userService.getUserById(SessionContextHolder.getUserId());
		model.addAttribute("user", user);
		return "user/edit";
	}

	/**
	 * 修改秀客信息
	 * @param user
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/users/update", method = RequestMethod.GET)
	public String updateUser(User user, Model model) {
		try {
			user.setId(SessionContextHolder.getUserId());
			userService.updateUser(user);
		} catch (Exception e) {
			model.addAttribute("sysError", "修改秀客出错");
		}
		return "redirect:/home";
	}

	/**
	 * 转到修改密码页面
	 * @return
	 */
	@RequestMapping(value = "/users/password/change", method = RequestMethod.GET)
	public String password() {
		return "user/resetPwd";
	}

	/**
	 * 重置密码
	 * @param user
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/users/password/change", method = RequestMethod.POST)
	public String resetPwd(@RequestParam("newPwd") String newPwd, @RequestParam("userPwd") String oldPwd, Model model) {
		User oldUser = userService.getUserByCode(SessionContextHolder.currentUser().getEmail());
		if (null == oldUser) {
			model.addAttribute("msg", "用户不存在");
			return "user/resetPwd";
		}
		if (!oldUser.getPassword().equals(oldPwd)) {
			model.addAttribute("msg", "旧密码不正确");
			return "user/resetPwd";
		}
		try {
			userService.updateUserPwd(newPwd, SessionContextHolder.currentUser().getUserId());
		} catch (Exception e) {
			model.addAttribute("msg", "修改密码保存出错");
			return "user/resetPwd";
		}
		return "redirect:/home";
	}

}
